package com.heima.comment.service.impl;

import com.heima.comment.dto.ApCommentRepay;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        // 判断用户是否登录
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 安全过滤--阿里云文本审核
        ApCommentRepay comment = new ApCommentRepay();
        comment.setUserId(user.getUserId());
        // 根据用户id查询用户,调用用户微服务提供的远程接口
        ResponseResult<ApUser> userResponseResult = userFeign.getById(user.getUserId());
        if (userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = userResponseResult.getData();
            comment.setUserName(apUser.getName());
        }
        comment.setCommentId(dto.getCommentId());
        comment.setContent(dto.getContent());
        comment.setLikes(0);
        comment.setCreatedTime(new Date());
        // 保存评论
        mongoTemplate.save(comment);
        // 将评论表的回复数量+1
        Query commentQuery = new Query();
        commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        // 更新条件
        Update update = new Update();
        update.inc("repay");
        mongoTemplate.updateFirst(commentQuery,update, ApComment.class);

        return ResponseResult.okResult();
    }
}
